using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Globalization;

namespace MM7.MIME.Encoding
{
	internal class QPEncoding  : MIMEEncoding
	{
		public const int RFC_1521_MAX_CHARS_PER_LINE = 75;

		internal override byte[] Encode(byte[] s)
		{
			StringBuilder sb = new StringBuilder();
			for(int i=0; i<s.Length; i++)
			{
				if (i%RFC_1521_MAX_CHARS_PER_LINE == RFC_1521_MAX_CHARS_PER_LINE-1) sb.Append("=\r\n");
				if ((s[i]>=33 && s[i]<=60) || (s[i]>=62 && s[i]<=126)) sb.Append((char)s[i]);
				else
				{
					sb.Append("=");
					sb.Append(s[i].ToString("X2"));
				}
			}

			System.Text.Encoding sss = System.Text.Encoding.GetEncoding("ISO8859-1");
			return sss.GetBytes(sb.ToString());
		}

		internal override byte[] Decode(byte[] bytes)
		{
			StringBuilder sb = new StringBuilder();
			System.Text.Encoding sss = System.Text.Encoding.GetEncoding("ISO8859-1");
			string encoded = sss.GetString(bytes);
			encoded = encoded.Replace("=\r\n","");
			int i = 0;
			int j = 0;
			do
			{
				j = encoded.IndexOf("=", i);
				if (j == -1) sb.Append(encoded.Substring(i));
				else
				{
					sb.Append(encoded.Substring(i, j-i));
					if(j <= encoded.Length-3)
					{
						string aaaaaa = encoded.Substring(j+1, 2);
						byte asdf  = byte.Parse(aaaaaa, NumberStyles.HexNumber);
						sb.Append((char)asdf);
						j = j + 3;
					}
					else
					{
						j = encoded.Length;
					}
				}
				i = j;
			}while(i != -1);
			return sss.GetBytes(sb.ToString());
		}

		internal override String ContentTransferEncodingString
		{
			get {return "quoted-printable";}
		}




	}
}
